<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"wan-lei8.gitee.io","root":"/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="合理使用Optional在Java代码里，由于NullPointerException不属于强制捕捉的异常，它会隐藏在代码里，造成很多不可预料的bug。所以，我们会在拿到一个参数的时候，都会验证它的合法性，看一下它到底是不是null，代码中到处充满了这样的代码。 123456789101112131415161718if(null &#x3D;&#x3D; obj)if(null &#x3D;&#x3D; user.getName()">
<meta property="og:type" content="article">
<meta property="og:title" content="Java8新特性Optional使用">
<meta property="og:url" content="https://wan-lei8.gitee.io/2020/03/23/Java8%E6%96%B0%E7%89%B9%E6%80%A7Optional%E4%BD%BF%E7%94%A8/index.html">
<meta property="og:site_name" content="程序员西桐">
<meta property="og:description" content="合理使用Optional在Java代码里，由于NullPointerException不属于强制捕捉的异常，它会隐藏在代码里，造成很多不可预料的bug。所以，我们会在拿到一个参数的时候，都会验证它的合法性，看一下它到底是不是null，代码中到处充满了这样的代码。 123456789101112131415161718if(null &#x3D;&#x3D; obj)if(null &#x3D;&#x3D; user.getName()">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-03-23T03:01:06.000Z">
<meta property="article:modified_time" content="2021-12-23T03:24:11.993Z">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://wan-lei8.gitee.io/2020/03/23/Java8%E6%96%B0%E7%89%B9%E6%80%A7Optional%E4%BD%BF%E7%94%A8/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Java8新特性Optional使用 | 程序员西桐</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">程序员西桐</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">但行好事，莫问前程</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wan-lei8.gitee.io/2020/03/23/Java8%E6%96%B0%E7%89%B9%E6%80%A7Optional%E4%BD%BF%E7%94%A8/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.png">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="程序员西桐">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Java8新特性Optional使用
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-03-23 11:01:06" itemprop="dateCreated datePublished" datetime="2020-03-23T11:01:06+08:00">2020-03-23</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-12-23 11:24:11" itemprop="dateModified" datetime="2021-12-23T11:24:11+08:00">2021-12-23</time>
              </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h3 id="合理使用Optional"><a href="#合理使用Optional" class="headerlink" title="合理使用Optional"></a>合理使用Optional</h3><p>在Java代码里，由于NullPointerException不属于强制捕捉的异常，它会隐藏在代码里，造成很多不可预料的bug。所以，我们会在拿到一个参数的时候，都会验证它的合法性，看一下它到底是不是null，代码中到处充满了这样的代码。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span>(<span class="keyword">null</span> == obj)</span><br><span class="line"><span class="keyword">if</span>(<span class="keyword">null</span> == user.getName() || <span class="string">&quot;&quot;</span>.equals(user.getName()))</span><br><span class="line">    </span><br><span class="line"><span class="keyword">if</span> (order != <span class="keyword">null</span>) &#123;</span><br><span class="line">    Logistics logistics = order.getLogistics();</span><br><span class="line">    <span class="keyword">if</span>(logistics != <span class="keyword">null</span>)&#123;</span><br><span class="line">        Address address = logistics.getAddress();</span><br><span class="line">        <span class="keyword">if</span> (address != <span class="keyword">null</span>) &#123;</span><br><span class="line">            Country country = address.getCountry();</span><br><span class="line">            <span class="keyword">if</span> (country != <span class="keyword">null</span>) &#123;</span><br><span class="line">                Isocode isocode = country.getIsocode();</span><br><span class="line">                <span class="keyword">if</span> (isocode != <span class="keyword">null</span>) &#123;</span><br><span class="line">                    <span class="keyword">return</span> isocode.getNumber();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Java8引入了Optional类，用于解决臭名昭著的空指针问题。实际上，它是一个包裹类，提供了几个方法可以去判断自身的空值问题。</p>
<p>上面比较复杂的代码示例，就可以替换成下面的代码。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">String result = Optional.ofNullable(order)</span><br><span class="line">     .flatMap(order-&gt;order.getLogistics())</span><br><span class="line">     .flatMap(logistics -&gt; logistics.getAddress())</span><br><span class="line">     .flatMap(address -&gt; address.getCountry())</span><br><span class="line">     .map(country -&gt; country.getIsocode())</span><br><span class="line">     .orElse(Isocode.CHINA.getNumber());</span><br></pre></td></tr></table></figure>

<p>当你不确定你提供的东西，是不是为空的时候，一个好的习惯是不要返回null，否则调用者的代码将充满了null的判断。我们要把null消灭在萌芽中。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Optional&lt;String&gt; <span class="title">getUserName</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> Optional.ofNullable(userName);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>另外，我们要尽量的少使用Optional的get方法，它同样会让代码变丑。比如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Optional&lt;String&gt; userName = <span class="string">&quot;xjjdog&quot;</span>;</span><br><span class="line">String defaultEmail = userName.get() == <span class="keyword">null</span> ? <span class="string">&quot;&quot;</span>:userName.get() + <span class="string">&quot;@xjjdog.cn&quot;</span>;</span><br></pre></td></tr></table></figure>

<p>而应该修改成这样的方式：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Optional&lt;String&gt; userName = <span class="string">&quot;xjjdog&quot;</span>;</span><br><span class="line">String defaultEmail = userName</span><br><span class="line">    .map(e -&gt; e + <span class="string">&quot;@xjjdog.cn&quot;</span>)</span><br><span class="line">    .orElse(<span class="string">&quot;&quot;</span>);</span><br></pre></td></tr></table></figure>


    </div>
<div>
  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

  
</div>

    
    
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://wan-lei8.gitee.io/2020/03/23/Java8%E6%96%B0%E7%89%B9%E6%80%A7Optional%E4%BD%BF%E7%94%A8/" title="Java8新特性Optional使用">https://wan-lei8.gitee.io/2020/03/23/Java8新特性Optional使用/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2019/12/17/WorkSummary-UserAuthenticationInfo/" rel="prev" title="WorkSummary_UserAuthenticationInfo">
      <i class="fa fa-chevron-left"></i> WorkSummary_UserAuthenticationInfo
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/05/22/Linux%E8%BF%9E%E6%8E%A5%E5%B7%A5%E5%85%B7/" rel="next" title="Linux连接工具">
      Linux连接工具 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%90%88%E7%90%86%E4%BD%BF%E7%94%A8Optional"><span class="nav-number">1.</span> <span class="nav-text">合理使用Optional</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt=""
      src="/images/avatar.png">
  <p class="site-author-name" itemprop="name"></p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives">
          <span class="site-state-item-count">41</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/yourname" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;yourname" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="/malegod958@163.com" title="E-Mail → malegod958@163.com"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2018 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">万磊</span>
</div>
  <div class="powered-by">

  </div>

        








      </div>
    </footer>
  </div>

  
  
  <script color='' opacity='0.5' zIndex='-1' count='99' src="/lib/canvas-nest/canvas-nest.min.js"></script>
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

  
	<script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
	

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/clicklove.js"></script>
